package logic

import (
	"context"
	"net/http"
	"path/filepath"
	"time"
	"user-profile/pkg"

	"user-profile/api/internal/svc"
	"user-profile/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ImageLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewImageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ImageLogic {
	return &ImageLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ImageLogic) Image(req *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	file, m, err := req.FormFile("image")
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Code:    500,
			Data:    nil,
		}, nil
	}
	ext := filepath.Ext(m.Filename)
	if ext == "jpeg" && ext == "png" {
		return &types.Response{
			Message: "图片格式不正确",
			Code:    500,
			Data:    nil,
		}, nil
	}
	if m.Size >= 8*1024*1024 {
		return &types.Response{
			Message: "文件过大,最大接收8MB",
			Code:    500,
			Data:    nil,
		}, nil
	}
	fileName := time.Now().Format("20060102150405") + ext
	yun, err := pkg.QiNIuYun(fileName, file)
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Code:    500,
			Data:    nil,
		}, nil
	}
	return &types.Response{
		Message: "图片上传成功",
		Code:    200,
		Data:    yun,
	}, nil
}
